#!/bin/bash

db=${1}
dir=${db%.db}

if test -d ${dir}; then echo "directory exists."; exit 1; fi

files=$(sqlite3 ${db} "select distinct file from path")

for i in $files; do
  if test -e ${dir}/${i}; then
      echo "file ${dir}/${i} exists.";
      exit 1;
  fi;
done

echo "Building directory ("$(echo $files | wc -w)")";
mkdir -p ${dir}

for i in $files; do
  file=${dir}/"${i}"
  mkdir -p $(dirname "$file")
  echo "$file"
  sqlite3 ${db} "select content from path where file='${i}' order by rowid desc limit 1" > "${file}"
done
echo "... done."
